import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'

import copy from 'rollup-plugin-copy';

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {




  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV } = env
  return {

    optimizeDeps: {
      include: ['@babel/preset-env'],
    },
    build: {
      rollupOptions: {
        input: {
          main: path.resolve(__dirname, 'index.html'),
          // nested: path.resolve(__dirname, 'nested/index.html')
        },
        output: {
          entryFileNames: 'js/[name]-[hash].js',
          chunkFileNames: 'js/chunk-[hash].js',
          assetFileNames: 'assets/[name]-[hash][extname]',
        },
        plugins: [
          copy({
            targets: [
              { src: 'src/utils/gisAddress.js', dest: 'dist/src' } // 将文件复制到输出目录
            ],
            verbose: true,
            hook: 'writeBundle'
          })
        ]
      }
    },
    // exclude: [
    //   // 排除某个文件
    //   'src/utils/gisAddress.js',
    // ],

    // 部署生产环境和开发环境下的URL。
    // 默认情况下，vite 会假设你的应用是被部署在一个域名的根路径上
    base: VITE_APP_ENV === 'production' ? './' : '/',
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src'),
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    // vite 相关配置
    server: {
      port: 80,
      host: true,
      open: true,
      proxy: {
        // http://10.1.6.107:30012/prod-api
        // https://cn.vitejs.dev/config/#server-proxy
        '/dev-api': {
          target: 'http://127.0.0.1:9306/',
          // target: 'https://2097675gx6.vicp.fun/',
          // target: 'http://2155xi2384.vicp.fun/',
          // target: 'http://192.168.1.10:9306/',
          // target: 'http://10.1.6.107:30020/',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ''),
        },
        // [process.env.VITE_APP_BASE_API]: {
        //   target: process.env.VITE_TARGET,
        //   changeOrigin: true,
        //   pathRewrite: {
        //     ['^' + process.env.VITE_APP_BASE_API]: '',
        //   },
        // },
      },
    },
    //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              },
            },
          },
        ],
      },
    },
  }
})
